﻿using StationDataHub.Services;

namespace StationDataHub.TimeJob;

public class QueryStationInfoJob(IFlurlClientCache client,
    IEasyCachingProvider cache,
    IDbService dbService) : IJob
{
    private readonly IFlurlClient _client = client.Get("ChargePlatform");
    private readonly IEasyCachingProvider _cache = cache;
    private readonly IDbService _dbService = dbService;

    public async Task Execute(IJobExecutionContext context)
    {
        try
        {
            var cfg = AppSettings.ChargePlatform.SecurityConfig;
            // 读取缓存中的 token
            var tokenCache = await _cache.GetAsync<string>("ChargePlatformToken");
            if (!tokenCache.HasValue || string.IsNullOrWhiteSpace(tokenCache.Value))
            {
                Log.Error("[查询充电站信息]Token 不存在或已过期，跳过本次任务");
                return;
            }

            int pageSize = 50; // 每页50条数据，减少请求次数
            int pageNo = 1; // 从第一页开始

            // 循环获取所有数据，直到没有更多页面
            while (true)
            {
                // 构造请求体
                var reqBody = new
                {
                    PageNo = pageNo.ToString(),
                    PageSize = pageSize.ToString()
                }.BuildEncryptedRequest();

                // 发送请求
                var response = await _client.Request(AppSettings.ChargePlatform.API.Interfaces.QueryStationInfo)
                    .WithHeader("Authorization", $"Bearer {tokenCache.Value}")
                    .PostJsonAsync(reqBody)
                    .ReceiveString();

                // 解析响应
                var resp = JsonSerializer.Deserialize<APIResponse>(response);
                if (resp != null && resp.Ret == 0 && !string.IsNullOrEmpty(resp.Data))
                {
                    var decryptedData = resp.Data.DecryptAES(cfg.AesEncryptionKey, cfg.AesInitialVector);
                    var stationsData = JsonSerializer.Deserialize<QueryStationsResponse>(decryptedData);

                    // 如果有数据，处理并入库
                    if (stationsData.StationInfos != null && stationsData.StationInfos.Count > 0)
                    {
                        Log.Information($"获取充电站信息：第 {pageNo} 页，共 {stationsData.ItemSize} 条");
                        await _dbService.InsertOrUpdateAsync(stationsData);
                    }

                    // 如果当前页数小于总页数，继续请求下一页
                    if (pageNo < stationsData.PageCount)
                    {
                        pageNo++;
                    }
                    else
                    {
                        // 如果是最后一页，跳出循环
                        break;
                    }
                }
                else
                {
                    Log.Error($"充电站入库执行异常: Ret={resp?.Ret}, Msg={resp?.Msg}");
                    break; // 发生错误时跳出循环
                }
            }
            //// 构造请求体
            //var reqBody = new
            //{
            //    //LastQueryTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss")
            //    PageNo = "1",
            //    PageSize = "10"
            //}.BuildEncryptedRequest();
            //// 发送请求
            //var response = await _client.Request(AppSettings.ChargePlatform.API.Interfaces.QueryStationInfo)
            //    .WithHeader("Authorization", $"Bearer {tokenCache.Value}")
            //    .PostJsonAsync(reqBody)
            //    .ReceiveString();

            //// 解析响应
            //var resp = JsonSerializer.Deserialize<APIResponse>(response);
            //if (resp != null && resp.Ret == 0 && !string.IsNullOrEmpty(resp.Data))
            //{
            //    var decryptedData = resp.Data.DecryptAES(cfg.AesEncryptionKey, cfg.AesInitialVector);
            //    var stationsData = JsonSerializer.Deserialize<QueryStationsResponse>(decryptedData);
            //    Log.Information("获取充电站信息：{0} 条", stationsData.ItemSize);
            //    // 入库
            //    await _dbService.InsertOrUpdateAsync(stationsData);
            //}
            //else
            //{
            //    Log.Error("充电站入库执行异常: Ret={0}, Msg={1}", resp?.Ret, resp?.Msg);
            //}
        }
        catch (Exception ex)
        {
            Log.Error(ex, $"查询充电站任务执行异常:{ex.Message}");
        }
    }
}